package org.codefinger.dao.impl.sql.ast;

import java.util.Iterator;

import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.Expression;

public class NamedListExpression implements Expression {

	private String	param;

	public NamedListExpression(String param) {
		super();
		this.param = param;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean matchVisit(SQLVisitor visitor) {
		Object obj = visitor.getParam(param);
		if (obj == null) {
			return false;
		}
		Iterator<Object> iterator;
		Object item;
		if (obj instanceof Iterable) {
			iterator = ((Iterable<Object>) obj).iterator();
			boolean flag = false;
			while (iterator.hasNext()) {
				item = iterator.next();
				if (item == null) {
					continue;
				}
				if (flag) {
					visitor.addParam(item);
					visitor.appendSQL(",?");
				} else {
					visitor.addParam(item);
					visitor.appendSQL("?");
					flag = true;
				}
			}
			return flag;
		}
		visitor.addParam(obj);
		visitor.appendSQL('?');
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void visit(SQLVisitor visitor) {
		Object obj = visitor.getParam(param);
		if (obj == null) {
			visitor.addParam(obj);
			visitor.appendSQL("?");
			return;
		}
		Iterator<Object> iterator;
		if (obj instanceof Iterable) {
			iterator = ((Iterable<Object>) obj).iterator();
			if (iterator.hasNext()) {
				visitor.addParam(iterator.next());
				visitor.appendSQL('?');
				while (iterator.hasNext()) {
					visitor.addParam(iterator.next());
					visitor.appendSQL(",?");
				}
			} else {
				visitor.addParam(null);
				visitor.appendSQL("?");
			}
			return;
		}
		visitor.addParam(obj);
		visitor.appendSQL('?');
	}

}
